package com.lagou.service;

import com.lagou.handler.UserServerHandler;
import com.lagou.service.common.RpcDecoder;
import com.lagou.service.common.RpcEncoder;
import com.lagou.service.pojo.RpcRequest;
import com.lagou.service.seriallzer.JSONSerializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.stereotype.Service;

/**
 * 实现rpc-consumer 公共方法
 */
@Service
public class UserServiceImpl implements IUserService {

    /**
     * 将来客户端要远程调用的方法
     * @param msg
     * @return
     */
    public String sayHello(String msg) {
        System.out.println("调用参数成功"+msg);
        return "调用参数成功："+msg;
    }

    //创建启动服务的方法
    public static void startServer(String ip, int port) throws InterruptedException {
        EventLoopGroup boosGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        ServerBootstrap serverBootstrap= new ServerBootstrap();
        serverBootstrap.group(boosGroup,workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    protected void initChannel(NioSocketChannel channel) throws Exception {
                        ChannelPipeline pipeline = channel.pipeline();
                        //写出去的：编码时使用字符串进行编码
                        pipeline.addLast( new StringEncoder());
                        //接受到的：解码使用自定义解码
                        pipeline.addLast( new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new UserServerHandler());
                    }
                });

         serverBootstrap.bind(ip,port).sync();
        System.out.println("服务启动");


    }
}
